<template>
  <div>
    <all-header :title="'全部电影'"></all-header>
    <all-choose :title="'全部分类'" :list="classNames" class="choose" @choose="classChange"/>
    <all-choose :title="'全部地区'" :list="areaNames" @choose="areaChange"/>
    <all-list :list="movieList" class="movie-list"/>
    <top :show="topShow"/>
  </div>
</template>
<script>
import AllHeader from 'common/header/Header'
import AllList from 'common/List'
import AllChoose from './components/Choose'
import Top from 'common/Top'
import axios from 'axios'
import qs from 'qs'
export default {
  name: 'AllMovie',
  components: {
    AllHeader,
    AllList,
    AllChoose,
    Top
  },
  data () {
    return {
      className: '',
      areaName: '',
      movieList: [],
      classNames: [],
      areaNames: [],
      page: 1,
      isLoading: false,
      topShow: false,
      changed: false
    }
  },
  methods: {
    getMovieList () {
      if (this.changed) {
        this.page = 1
      }
      this.isLoading = true
      let obj = { page_request: this.page }
      if (this.className) obj.class = this.className
      if (this.areaName) obj.area = this.areaName
      axios.post('/api/allClass', qs.stringify(obj)).then(this.getListSucc)
    },
    getListSucc (res) {
      if (this.changed) {
        this.movieList = []
        this.changed = false
      }
      res = res.data
      this.movieList = this.movieList.concat(res.data.movieList)
      this.isLoading = false
    },
    classChange (newName) {
      this.className = newName
    },
    areaChange (newName) {
      this.areaName = newName
    },
    getClassName () {
      axios.get('/api/static/classNames').then(this.getClassSucc)
    },
    getClassSucc (res) {
      res = res.data
      this.classNames = res.data.classNames
    },
    getAreaName () {
      axios.get('/api/static/areaNames').then(this.getAreaSucc)
    },
    getAreaSucc (res) {
      res = res.data
      this.areaNames = res.data.areaNames
    },
    handleScroll () {
      let clientHeight = document.documentElement.clientHeight
      let scrollHeight = document.body.scrollHeight
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      let preDis = 30
      if (clientHeight + scrollTop > scrollHeight - preDis) {
        if (!this.isLoading) {
          ++this.page
          this.getMovieList()
        }
      }
      if (scrollTop > 20) {
        this.topShow = true
      } else {
        this.topShow = false
      }
    }
  },
  watch: {
    className () {
      this.changed = true
      this.getMovieList()
    },
    areaName () {
      this.changed = true
      this.getMovieList()
    }
  },
  mounted () {
    this.getMovieList()
    this.getClassName()
    this.getAreaName()
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
<style lang="stylus" scoped>
  .choose
    margin-top: .6rem
</style>
